const Controller = require('egg').Controller;

class ConversationController extends Controller {
  // 创建或获取会话
  async createOrGet() {
    const { ctx, service } = this;
    
    try {
      // 参数验证
      const rules = {
        target_user_id: { type: 'number', required: true }
      };
      ctx.validate(rules);
      
      const { target_user_id } = ctx.request.body;
      
      // 从token获取当前用户ID
      const token = ctx.request.header.token;
      const decode = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);
      const userId = decode.user_id;
      
      // 转换为数字进行比较
      const targetUserId = parseInt(target_user_id);
      
      // 不能和自己创建会话
      if (userId === targetUserId) {
        throw new Error('不能和自己创建会话');
      }
      
      const conversation = await service.conversation.createOrGetConversation(userId, targetUserId);
      
      ctx.body = {
        code: 0,
        data: conversation,
        msg: '获取会话成功'
      };
    } catch (error) {
      if (error.errors) {
        ctx.body = {
          code: 1,
          data: null,
          msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
        };
        return;
      }
      
      ctx.body = {
        code: 1,
        data: null,
        msg: error.message || '获取会话失败'
      };
    }
  }
  
  // 获取用户的会话列表
  async list() {
    const { ctx, service } = this;
    
    try {
      // 从token获取当前用户ID
      const token = ctx.request.header.token;
      const decode = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);
      const userId = decode.user_id;
      
      const result = await service.conversation.getUserConversations(userId, ctx.query);
      
      ctx.body = {
        code: 0,
        data: result,
        msg: '获取会话列表成功'
      };
    } catch (error) {
      ctx.body = {
        code: 1,
        data: null,
        msg: error.message || '获取会话列表失败'
      };
    }
  }
  
  // 获取会话详情
  async detail() {
    const { ctx, service } = this;
    
    try {
      const { id } = ctx.params;
      
      // URL参数是字符串，转换为数字
      const conversationId = parseInt(id);
      
      if (isNaN(conversationId)) {
        throw new Error('会话ID格式错误');
      }
      
      // 从token获取当前用户ID
      const token = ctx.request.header.token;
      const decode = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);
      const userId = decode.user_id;
      
      const conversation = await service.conversation.getConversationDetail(conversationId, userId);
      
      ctx.body = {
        code: 0,
        data: conversation,
        msg: '获取会话详情成功'
      };
    } catch (error) {
      if (error.errors) {
        ctx.body = {
          code: 1,
          data: null,
          msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
        };
        return;
      }
      
      ctx.body = {
        code: 1,
        data: null,
        msg: error.message || '获取会话详情失败'
      };
    }
  }
  
  // 关闭会话
  async close() {
    const { ctx, service } = this;
    
    try {
      const { id } = ctx.params;
      
      // URL参数是字符串，转换为数字
      const conversationId = parseInt(id);
      
      if (isNaN(conversationId)) {
        throw new Error('会话ID格式错误');
      }
      
      // 从token获取当前用户ID
      const token = ctx.request.header.token;
      const decode = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);
      const userId = decode.user_id;
      
      await service.conversation.closeConversation(conversationId, userId);
      
      ctx.body = {
        code: 0,
        data: null,
        msg: '关闭会话成功'
      };
    } catch (error) {
      if (error.errors) {
        ctx.body = {
          code: 1,
          data: null,
          msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
        };
        return;
      }
      
      ctx.body = {
        code: 1,
        data: null,
        msg: error.message || '关闭会话失败'
      };
    }
  }
  
  // 重置未读计数
  async resetUnread() {
    const { ctx, service } = this;
    
    try {
      const { id } = ctx.params;
      
      // URL参数是字符串，转换为数字
      const conversationId = parseInt(id);
      
      if (isNaN(conversationId)) {
        throw new Error('会话ID格式错误');
      }
      
      // 从token获取当前用户ID
      const token = ctx.request.header.token;
      const decode = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);
      const userId = decode.user_id;
      
      const conversation = await service.conversation.resetUnreadCount(conversationId, userId);
      
      ctx.body = {
        code: 0,
        data: conversation,
        msg: '重置未读计数成功'
      };
    } catch (error) {
      if (error.errors) {
        ctx.body = {
          code: 1,
          data: null,
          msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
        };
        return;
      }
      
      ctx.body = {
        code: 1,
        data: null,
        msg: error.message || '重置未读计数失败'
      };
    }
  }
}

module.exports = ConversationController;